package com.xc.smart.utlis;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.reactive.HandlerMapping;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 响应返回工具
 * @author mtl
 * 2021/4/25
 */
@Slf4j
public class RequestUtils {

    /**
     * @Title: out
     * @Description:  response输出JSON数据
     * @param response : 响应请求
     * @param object: object
     * @return void
     **/
    public static void out(ServletResponse response, Object object){
        PrintWriter out = null;
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.println(object);
        } catch (Exception e) {
            log.error("输出JSON报错!"+e);
        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }
    /**
     * 获取所有的请求头
     * @param request
     * @return
     */
    public static Map<String,String> getHeaders(HttpServletRequest request){
        Map<String,String> headerMap = new HashMap<>();
        List<String> headers = getCommonHeaders();
        headers.add("Postman-Token");
        headers.add("Proxy-Connection");
        headers.add("X-Lantern-Version");
        headers.add("Cookie");

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            if (headers.contains(headerName)){
                continue;
            }
            headerMap.put(headerName,request.getHeader(headerName));
        }
        return headerMap;
    }

    /**
     * 获取请求的路径参数
     * @param request
     * @return
     */
    public static Map<String, String> getUriTemplateVar(HttpServletRequest request) {
        NativeWebRequest webRequest = new ServletWebRequest(request);
        Map<String, String> uriTemplateVars = (Map<String, String>) webRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

        return uriTemplateVars;
    }

    /**
     * 获取请求的真实IP
     * @param request
     * @return
     */
    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    private static List<String> getCommonHeaders(){
        List<String> headers = new ArrayList<>();
        Class<HttpHeaders> clazz = HttpHeaders.class;
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getType().toString().endsWith("java.lang.String") && Modifier.isStatic(field.getModifiers())){
                try {
                    headers.add((String) field.get(HttpHeaders.class));
                } catch (IllegalAccessException e) {
                    log.error("反射获取属性值异常-->",e);
                }
            }
        }
        return headers;
    }


}
